package com.nation.nationslidemenu;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.entity.mime.MultipartEntity;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.coe3.data.Information;
import com.coe3.datahandler.BaseActivity;
import com.coe3.datahandler.HttpConnection;
import com.coe3.datahandler.ParserXMLHandler;
import com.coe3.datahandler.ParserXMLHandler.ElementData;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;



import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class VdoActivity extends BaseActivity {

	AllIntent allintent=new AllIntent(VdoActivity.this);
	
	
	private ArrayList<String> img_url= new ArrayList<String>();
	private ArrayList<String> vdo_url= new ArrayList<String>();
	
	private Gallery gallery;
	private ImageView imageView1;
	private DisplayImageOptions options;
	private ImageGalleryAdapter  galleryAdapter=new ImageGalleryAdapter();
	private ImageLoader imageLoader = ImageLoader.getInstance();
	
	
	
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vdo);
		// Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        
        
        
        
        	String url = "http://www.nationmultimedia.com/new/rss/ipad_v2/ipad_vdo.xml";
      		//String url="http://www.nationmultimedia.com/new/rss/ipad_v2/photo.xml";
      		startConnection( url, "", HttpConnection.GET, -1, null );
        
      
        
        //allintent.OpenVDO("http://www.nationmultimedia.com/home/admin/specials/nationvdo/mp4/nlmIBWC.mp4");
        
      }

	//===========================Parser===============================
	@SuppressLint("HandlerLeak")
	public void startConnection( String url, String data , int method, final int handlerType, final MultipartEntity entity ) {
		Log.e("max", "MainActivity==========startConnection");
		Log.e("chud", "url: " + url);
		Log.e("chud", "data: " + data);
		
		Handler handler = new Handler() {
			@SuppressWarnings("deprecation")
			public void handleMessage(Message message) {
				switch ( message.what ) {
				case HttpConnection.DID_START:
						showDialog( DIALOG_CONNECTION_START );
					break;
				
				case HttpConnection.DID_SUCCEED:
					try {
						Log.e("chud", "(String)message.obj: " + (String)message.obj);
						startParseXMLResponse( (String)message.obj, handlerType );
					} catch ( Exception e ) {
						Log.e( "Connection Exception", "XML Pasing Excpetion : " + e );
		        		didFinishParsing();
					}
					
					break;
				
				case HttpConnection.DID_ERROR:
					Log.e( "Connection Error", "HTTP Connection did error : " + message.obj );
	        		showAlertBox( "Connection Error!!!", "Please try again." );
	        		didFinishParsing();
					break;
				}	
			}
		};

		HttpConnection connection = new HttpConnection(handler);
		if( entity != null )
			connection.setMultipartEntity( entity );
		connection.create(method, url, data);
	}

	public void startParseXMLResponse( String response, int handlerType ) throws SAXException, ParserConfigurationException, IOException {
		
		Log.e("max", "MainActivity==========startParseXMLResponse");
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = spf.newSAXParser();
		XMLReader xr = sp.getXMLReader();
		
		ParserXMLHandler parser = null;
		Handler handler = handlerInformation(handlerType);
		parser = new ParserXMLHandler( this, handler );
		
		StringReader sr = new StringReader(response);
		InputSource is = new InputSource(sr);
		
		xr.setContentHandler(parser);
		xr.parse(is);
	}
	
	private static Vector<NewData> mListNews = new Vector<NewData>();
	private NewData mItem = null;
	@SuppressLint("HandlerLeak")
	public Handler handlerInformation(final int handlerType) {
		
		Log.e("max", "MainActivity==========handlerInformation");
		
		Handler mHandler = new Handler() {
			public void handleMessage( Message message ) {
				ElementData data = ( ElementData )message.obj;
				switch( message.what ) {
					case ParserXMLHandler.START_DOCUMENT:
						
						mListNews.removeAllElements();
						
						break;
						
					case ParserXMLHandler.DID_START_ELEMENT:
						
						if( data.name.equalsIgnoreCase(NewData.TAG_ITEM) ) 
						{
							mItem = new NewData();
						}//end if
						
						if( data.attributes.containsKey(NewData.TAG_ENCLOSURE_URL) ) 
						{
							mItem.enclosure_url = Information.setData(data.attributes.get(NewData.TAG_ENCLOSURE_URL), Information.STR_EMPTY);
						}//end if
						
						if( data.attributes.containsKey(NewData.TAG_ENCLOSURE_TYPE) ) {
							mItem.enclosure_type = Information.setData(data.attributes.get(NewData.TAG_ENCLOSURE_TYPE), Information.STR_EMPTY);
						}//end if
						
						
						
						break;
						
					case ParserXMLHandler.DID_FINISH_ELEMENT:
						
						if( data.name.equalsIgnoreCase(NewData.TAG_TITLE) ) 
						{
							mItem.title = Information.setData(data.value, Information.STR_EMPTY);
						} 
						else if( data.name.equalsIgnoreCase(NewData.TAG_DESCRIPTION) ) 
						{
							mItem.description = Information.setData(data.value, Information.STR_EMPTY);
						}
						else if( data.name.equalsIgnoreCase(NewData.TAG_VIDEO) ) 
						{
							mItem.video = Information.setData(data.value, Information.STR_EMPTY);
						}
						else if( data.name.equalsIgnoreCase(NewData.TAG_ITEM) ) 
						{
							mListNews.add(mItem);
							mItem = null;
						}//end if
						
						break;
						
					case ParserXMLHandler.END_DOCUMENT:
						
						setNews(mListNews);
					    SetImageToGallery();
						break;
				}
			}
		};
			
		return mHandler;
	}
	public void setNews(Vector<NewData> listNews) {
		Log.e("max", "MainActivity==========setNews(Vector<NewData> listNews)");
		for (NewData newData : listNews) {
			Information.logDEBUG("title: " + newData.title);
			Information.logDEBUG("description: " + newData.description);
			Information.logDEBUG("enclosure_url: " + newData.enclosure_url);
			Information.logDEBUG("enclosure_type: " + newData.enclosure_type);
			Information.logDEBUG("video: " + newData.video);
			
			Log.e("max","enclosure_url="+ newData.enclosure_url);
			img_url.add(newData.enclosure_url);
			vdo_url.add(newData.video);

			
		}
		
		
	}
	
	
	
	
	//===============================Gallery===============================
    public static void initImageLoader(Context context) {
	// This configuration tuning is custom. You can tune every option, you may tune some of them, 
	// or you can create default configuration by
	//  ImageLoaderConfiguration.createDefault(this);
	// method.
	ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
			.threadPriority(Thread.NORM_PRIORITY - 2)
			.denyCacheImageMultipleSizesInMemory()
			.discCacheFileNameGenerator(new Md5FileNameGenerator())
			.tasksProcessingOrder(QueueProcessingType.LIFO)
			.enableLogging() // Not necessary in common
			.build();
	// Initialize ImageLoader with configuration.
	ImageLoader.getInstance().init(config);
}
	
	private void startImagePagerActivity(int position) {
		
		allintent.OpenVDO(vdo_url.get(position));
		
	}

	private class ImageGalleryAdapter extends BaseAdapter {
		
		ImageView imageView;
		
		@Override
		public int getCount() {
			return img_url.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			imageView = (ImageView) convertView;
			if (imageView == null) {
				imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_gallery_vdo, parent, false);
			}
			
			/*imageView.setOnClickListener(new OnClickListener() {
				@SuppressLint("NewApi")
				@Override
				public void onClick(View view) {

					imageView.setAlpha(3.0f);
					
					
				}
			});*/
			
			imageLoader.displayImage(img_url.get(position), imageView, options);
			return imageView;
		}
	}
	private void SetImageToGallery()
	{
		Bundle bundle = getIntent().getExtras();
		//imageUrls = bundle.getStringArray(Extra.IMAGES);
			imageView1=(ImageView)findViewById(R.id.imageView1);
		options = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.loading)
			.showImageForEmptyUri(R.drawable.ic_empty)
			.showImageOnFail(R.drawable.ic_error)
			.cacheInMemory()
			.cacheOnDisc()
			.bitmapConfig(Bitmap.Config.RGB_565)
			.build();
		
		
		
		initImageLoader(getApplicationContext());
		

		gallery = (Gallery) findViewById(R.id.gallery);
		gallery.setAdapter(galleryAdapter);
		gallery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				startImagePagerActivity(position);
				
			}
		});
		
	}
	

}